#include "plotform.h"
#include "ui_plotform.h"

#include <QFileDialog>
#include <QSplineSeries>
#include <QValueAxis>
#include <QSplineSeries>
#include <QDateTimeAxis>
#include <QMessageBox>


#ifdef WIN32

#else

#endif

PlotForm::PlotForm(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::PlotForm)
{
    ui->setupUi(this);
    initForm();
    initChart();
    //initChart2();
    initCheckBox();
}

PlotForm::~PlotForm()
{
    delete ui;
}

void PlotForm::initForm()
{
    ui->graphicsView_chart2->hide();
    //导入文件后，直接画图 + 保存到文件中
    connect(ui->pushButton_addFile, &QPushButton::clicked, this, [=](){
        //导入文件路径
        QString dataFilePath = QFileDialog::getOpenFileName(this, "选择文件", QDir::homePath(), "*.txt");
        if(!dataFilePath.isEmpty()){
            ui->lineEdit_filePath->setText(dataFilePath);
        }

        //导出的文件路径
        QFileInfo fileInfo(dataFilePath);
        QString outFilePath = fileInfo.absolutePath() + "/" + fileInfo.completeBaseName() + ".csv";


        QFile dataFile(dataFilePath);
        QFile outFile(outFilePath);

        QTextStream outStream(&outFile);
        QTextStream fileStream(&dataFile);

        QStringList strList;
        QDateTime dateTime;

        //解析数据
        if(!dataFile.open(QFile::ReadOnly) || !outFile.open(QFile::WriteOnly|QIODevice::Truncate)){
             QMessageBox::information(this, tr("文件打开失败"), tr("请重新导入"));
        }else{
            //解析float值的数据，绘制时间-响应值
            while(!fileStream.atEnd()){
                qDebug()<<__FILE__<<__LINE__;
                QString str = fileStream.readLine();
                if(str.isEmpty()){
                    continue;
                }
                strList = str.split("  ");
                if(strList.size() < 16){
                    qDebug()<<"col num  < 16, col num = "<<strList.size();
                    continue;
                }

                dateTime = QDateTime::fromString(strList[0], "yyyy/MM/dd HH:mm:ss");

                double atmosphericOpticalQuality = strList[14].toDouble();
                double correctionFactor = strList[15].toDouble();
                qDebug()<<strList[0]<<"----"<<dateTime;
                //dateTime.setDate(QDateTime::currentDateTime().date());

                QList<float> dataList;
                QList<double> dataList2;
                for(int i = 0; i < 9; ++i){
                    double tmpData = strList[i + 1].toDouble();
                    dataList.push_back(tmpData);
                    dataList2.push_back(log(tmpData/correctionFactor));
                }

                emit(SigPlotChart2(atmosphericOpticalQuality, dataList2));
                emit SigProtocol(dateTime, dataList);
            }


            /* 解析存储原始数据的文件 绘制 时间-响应值
            outStream<<QString("time,")<<QString("340nm,")<<QString("380nm,")<<QString("440nm,")
                      <<QString("500nm,")<<QString("675nm,")<<QString("870nm,")<<QString("936nm,")
                      <<QString("1020nm,")<<QString("1640nm,\n");//表头
            while(!fileStream.atEnd()){
                QString str = fileStream.readLine();
                if(str.isEmpty()){
                    continue;
                }
                strList = str.split("-");
                if(strList.size() < 2){
                    continue;
                }

                dateTime = QDateTime::fromString(strList[0], "yyyy:MM:dd HH:mm:ss");
                qDebug()<<strList[0]<<"----"<<dateTime;
                //dateTime.setDate(QDateTime::currentDateTime().date());
                QByteArray hexByte(strList[1].toLatin1());
                QByteArray byte = QByteArray::fromHex(hexByte);
                if(byte.size() < 44){
                    continue;
                }
                byte = byte.mid(6, 36);
                float pf[9] = {0};
                memcpy(pf, byte.data(), byte.size());

                //组装成QVector 交给绘图程序并写入csv文件中
                outStream<<dateTime.toString("yyyy/MM/dd HH:mm:ss,");
                QList<float> dataList;
                for(int i = 0; i < 9; ++i){
                    outStream<<QString::number(pf[i], 'f', 4)<<QString(",");
                    dataList.push_back(pf[i]);
                }
                outStream<<QString("\n");

                emit SigProtocol(dateTime, dataList);
            }
            */
        }
    });


}


static const char* series_name[SERIES_COUNT] = {
    "340nm",
    "380nm",
    "440nm",
    "500nm",
    "675nm",
    "870nm",
    "936nm",
    "1020nm",
    "1640nm",
    // "340nm",
    // "380nm",
    // "440nm",
    // "500nm",
    // "675nm",
    // "870nm",
    // "936nm",
    // "1020nm",
    // "1650nm",
    // "xxx"
};

void PlotForm::initChart()
{
    //initColor();

    m_chart = new QChart();

    QValueAxis *axisY = new QValueAxis();
    //m_yMax[0]保存m_series1和m_series10的所有数据的最大值，m_yMin[0]反之
    axisY->setRange(0, 100);
    axisY->setTickCount(6);
    axisY->setLabelFormat("%.2f");

    // 设置x轴
    QDateTimeAxis* axisX = new QDateTimeAxis;
    axisX->setTickCount(4);
    axisX->setFormat("yyyy/MM/dd hh:mm:ss");
    axisX->setRange(QDateTime::currentDateTime().addSecs(-60), QDateTime::currentDateTime().addSecs(60*60));

    m_chart->addAxis(axisX, Qt::AlignBottom);
    m_chart->addAxis(axisY, Qt::AlignmentFlag::AlignLeft);

    for(int i = 0; i < SERIES_COUNT; ++i){
        QLineSeries* series = new QLineSeries(m_chart);
        m_chart->addSeries(series);
        m_chart->series().at(i)->show();
        m_seriesList.append(series);
        series->attachAxis(axisX);
        series->attachAxis(axisY);
        series->setName(series_name[i]);
    }


    connect(this, &PlotForm::SigProtocol, this, [=](const QDateTime& datetime, const QList<float>& data){
        qint64 mSecondSince = datetime.toMSecsSinceEpoch();
        qDebug()<<QDateTime::fromMSecsSinceEpoch(mSecondSince);

        for(int i=0;i < 9;i++){

            if(data[i] > m_max){
                m_max = data[i];
            }

            if(m_min > data[i]){
                m_min = data[i];
            }

            double item = static_cast<double>(data[i]);
            m_seriesList[i]->append(mSecondSince, item);
        }



        axisY->setRange(static_cast<qreal>(m_min), static_cast<qreal>(m_max));

        axisX->setRange(datetime.addSecs(-60*60*0.5), datetime);
        //axisX->setRange(QDateTime::fromString("2024/09/12 11:00:00", "yyyy/MM/dd HH:mm:ss"), QDateTime::fromString("2024/09/12 13:00:00", "yyyy/MM/dd HH:mm:ss"));

        this->m_chart->update();
        ui->graphicsView_chart->update();
    });

    this->m_chart->setTheme(QChart::ChartTheme::ChartThemeBlueCerulean);

    //设置图例，在设置主题后设置
    QFont font = m_chart->legend()->font();
    font.setPointSizeF(20);
    m_chart->legend()->setFont(font);

    m_seriesList[0]->setColor(Qt::white);
    m_seriesList[1]->setColor(Qt::black);
    m_seriesList[2]->setColor(Qt::red);
    m_seriesList[3]->setColor(Qt::darkRed);
    m_seriesList[4]->setColor(Qt::green);
    m_seriesList[5]->setColor(Qt::darkGreen);
    m_seriesList[6]->setColor(Qt::blue);
    m_seriesList[7]->setColor(Qt::magenta);
    m_seriesList[8]->setColor(Qt::yellow);

    // for(int i = 0; i < 9; ++i){
    //     m_seriesList[i]->setPen(QPen(QBrush(m_colorList[i]), 2, Qt::SolidLine));
    // }
    // for(int i = 9; i < SERIES_COUNT; ++i){
    //     m_seriesList[i]->setPen(QPen(QBrush(m_colorList[i%m_colorList.size()]), 2, Qt::DashLine));
    // }


    ui->graphicsView_chart->setChart(m_chart);
    ui->graphicsView_chart->setRenderHint(QPainter::Antialiasing);
    ui->graphicsView_chart->update();
    this->m_chart->update();
}

void PlotForm::initChart2(){
    m_chart2 = new QChart();
    QValueAxis *axisY = new QValueAxis();
    axisY->setRange(0, 100);
    axisY->setTickCount(6);

    QValueAxis *axisX = new QValueAxis();
    axisY->setRange(0, 100);
    axisY->setTickCount(6);

    m_chart2->addAxis(axisX, Qt::AlignBottom);
    m_chart2->addAxis(axisY, Qt::AlignLeft);

    for(int i = 0; i < SERIES_COUNT; ++i){
        QLineSeries* series = new QLineSeries(m_chart2);
        m_chart2->addSeries(series);
        m_chart2->series().at(i)->show();
        m_seriesList2.append(series);
        series->attachAxis(axisX);
        series->attachAxis(axisY);
        series->setName(series_name[i]);
    }


    connect(this, &PlotForm::SigPlotChart2, this, [=](const double& dataX, const QList<double>& dataY){
        for(int i=0;i < 9;i++){
            if(m_chart2X_min > dataX){
                m_chart2X_min = dataX;
            }
            if(m_chart2X_max < dataX){
                m_chart2X_max = dataX;
            }
            if(m_chart2Y_min > dataY[i]){
                m_chart2Y_min = dataY[i];
            }
            if(m_chart2Y_max < dataY[i]){
                m_chart2Y_max = dataY[i];
            }

            m_seriesList2[i]->append(dataX, dataY[i]);
        }

        axisX->setRange(m_chart2X_min, m_chart2X_max);
        axisY->setRange(m_chart2Y_min, m_chart2Y_max);

        this->m_chart2->update();
        ui->graphicsView_chart2->update();
    });

    this->m_chart2->setTheme(QChart::ChartTheme::ChartThemeBlueCerulean);

    //设置图例，在设置主题后设置
    QFont font = m_chart->legend()->font();
    font.setPointSizeF(20);
    m_chart->legend()->setFont(font);

    m_seriesList2[0]->setColor(Qt::white);
    m_seriesList2[1]->setColor(Qt::black);
    m_seriesList2[2]->setColor(Qt::red);
    m_seriesList2[3]->setColor(Qt::darkRed);
    m_seriesList2[4]->setColor(Qt::green);
    m_seriesList2[5]->setColor(Qt::darkGreen);
    m_seriesList2[6]->setColor(Qt::blue);
    m_seriesList2[7]->setColor(Qt::magenta);
    m_seriesList2[8]->setColor(Qt::yellow);

    ui->graphicsView_chart2->setChart(m_chart2);
     ui->graphicsView_chart2->setRenderHint(QPainter::Antialiasing);
    ui->graphicsView_chart2->update();
    this->m_chart2->update();

}

void PlotForm::initCheckBox()
{

    m_checkBoxMap.insert(0, ui->checkBox_340nm);
    m_checkBoxMap.insert(1, ui->checkBox_380nm);
    m_checkBoxMap.insert(2, ui->checkBox_440nm);
    m_checkBoxMap.insert(3, ui->checkBox_500nm);
    m_checkBoxMap.insert(4, ui->checkBox_675nm);
    m_checkBoxMap.insert(5, ui->checkBox_870nm);
    m_checkBoxMap.insert(6, ui->checkBox_936nm);
    m_checkBoxMap.insert(7, ui->checkBox_1020nm);
    m_checkBoxMap.insert(8, ui->checkBox_1650nm);

    for(int i = 0; i < SERIES_COUNT; ++i){
        connect(m_checkBoxMap[i], &QCheckBox::stateChanged, this, [=](int state){
            if(0 == state){
                m_seriesList[i]->hide();
                m_seriesList2[i]->hide();
            }else{
                m_seriesList[i]->show();
                m_seriesList2[i]->show();
            }
        });
    }

}

void PlotForm::initColor()
{
    //色卡的颜色数量为Series的一半 , size = 10
    int size = (SERIES_COUNT / 2) + 1;

    //step = 360 / 5
    float step1 = 360.0f / static_cast<float>(size / 2.0f); // 色轮上每一步的角度

    //亮度和饱和度
    float minLight = 0.4f;
    float maxLight = 1.0f;
    float minSaturation = 0.4f;
    float maxSaturation = 0.8f;

    for (int i = 0; i < size / 2; ++i) {
        int hue = i * step1;
        // 创建颜色
        QColor color = QColor::fromHslF(hue / 360.0f, minLight, minSaturation);
        m_colorList.append(color);
        color = QColor::fromHslF(hue / 360.0f, maxLight, maxSaturation);
        m_colorList.append(color);
    }
}

void PlotForm::checkFileSize(const QString &path)
{
    QFileInfo fileInfo(path);
    QFile dataFile(path);
    qint64 fileSize = fileInfo.size(); // 获取文件大小（以字节为单位）
    if(FILE_MAX_SIZE_KB < fileSize/1024){
        QDateTime dt = QDateTime::currentDateTime();
    }
    dataFile.close();
}
